#include "../include/CTimer.h"

CTimer::CTimer()
{
    QueryPerformanceFrequency( (LARGE_INTEGER*)&m_ticksPerSecond );

    m_currentTime = m_lastTime = m_lastFPSUpdate = 0;
    m_numFrames = 0;
    m_runningTime = m_timeElapsed = m_fps = 0.0f;
    m_FPSUpdateInterval = m_ticksPerSecond >> 1;
    m_timerStopped = true; 
}

CTimer::~CTimer()
{

}

void CTimer::StartTimer(void)
{
    // If the timer is started already just return.
    if ( !m_timerStopped )
        return;
        
    QueryPerformanceCounter( (LARGE_INTEGER *)&m_lastTime );
    m_timerStopped = false; 
}

void CTimer::StopTimer(void)
{
    if ( m_timerStopped )
        return;
        
    long stopTime = 0;
    QueryPerformanceCounter( (LARGE_INTEGER *)&stopTime );
    m_runningTime += (float)(stopTime - m_lastTime) / (float)m_ticksPerSecond;
    m_timerStopped = true; 
}

void CTimer::UpdateTimer(void)
{
    // If the timer is stopped we dont need to be here.
    if (m_timerStopped)
        return;

    // Get the current time
    QueryPerformanceCounter( (LARGE_INTEGER *)&m_currentTime );

    // Calculate the elapsed time.
    m_timeElapsed = (float)(m_currentTime - m_lastTime) / (float)m_ticksPerSecond;
    m_runningTime += m_timeElapsed;

    // Update FPS
    m_numFrames++;
    if ( m_currentTime - m_lastFPSUpdate >= m_FPSUpdateInterval )
    {
        float currentTime = (float)m_currentTime / (float)m_ticksPerSecond;
        float lastTime = (float)m_lastFPSUpdate / (float)m_ticksPerSecond;
        m_fps = (float)m_numFrames / (currentTime - lastTime);

        m_lastFPSUpdate = m_currentTime;
        m_numFrames = 0;
    }

    m_lastTime = m_currentTime;
}
